package com.easemob.helpdesk.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.activity.UserActivity;
import com.easemob.helpdesk.bean.OwnerInfoRes;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.bean.UserInfo;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.R;
import com.easemob.helpdesk.emoticon.utils.SimpleCommonUtils;
import com.easemob.helpdesk.listener.OnItemClickListener;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DateUtils;
import com.hyphenate.kefusdk.HDDataCallBack;
//import com.hyphenate.kefusdk.bean.HDSession;
import com.hyphenate.kefusdk.chat.HDClient;
//import com.hyphenate.kefusdk.entity.HDImageMessageBody;
import com.hyphenate.kefusdk.entity.HDMessage;
//import com.hyphenate.kefusdk.entity.HDNormalFileMessageBody;
//import com.hyphenate.kefusdk.entity.HDTextMessageBody;
//import com.hyphenate.kefusdk.entity.HDVideoMessageBody;
//import com.hyphenate.kefusdk.entity.HDVoiceMessageBody;
import com.hyphenate.kefusdk.entity.HDSession;
import com.hyphenate.kefusdk.gsonmodel.customer.CustomerInfoResponse;
import com.hyphenate.kefusdk.manager.session.CurrentSessionManager;
import com.hyphenate.kefusdk.messagebody.HDImageMessageBody;
import com.hyphenate.kefusdk.messagebody.HDNormalFileMessageBody;
import com.hyphenate.kefusdk.messagebody.HDTextMessageBody;
import com.hyphenate.kefusdk.messagebody.HDVideoMessageBody;
import com.hyphenate.kefusdk.messagebody.HDVoiceMessageBody;
import com.hyphenate.kefusdk.utils.MessageUtils;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.housekeeperapp.R.id.originType;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

/**
 * Created by lyuzhao on 2015/12/10.
 */
public class CurrentSessionAdapter extends RecyclerView.Adapter<CurrentSessionAdapter.MyViewHolder> implements Filterable {
	private static final String TAG = "CurrentSessionAdapter";
	private Context mContext;
	private FragmentActivity mActivity;
	public OnItemClickListener clickListener;
	private List<HDSession> sessionList;
//	private List<String> addrList = new ArrayList<>();
	Map<Integer, String> addrList = new HashMap<Integer, String>();
	Map<Integer, String> nameList = new HashMap<Integer, String>();

	private HDSession[] sessions;
	private Filter mFilter;
	private static final int HANDLER_MESSAGE_REFRESH_LIST = 0;

	private SwipeRefreshLayout mSwipeLayout;

	private WeakHandler handler;

	private static class WeakHandler extends Handler {
		WeakReference<CurrentSessionAdapter> weakReference;

		public WeakHandler(CurrentSessionAdapter adapter) {
			this.weakReference = new WeakReference<CurrentSessionAdapter>(adapter);
		}

		private void refreshList() {
			CurrentSessionAdapter adapter = weakReference.get();
			if (adapter == null){
				Log.d(TAG, "refreshList: adapter-------- null");

			}else{

				Log.d(TAG, "refreshList: adatper not null--------");
			}
			if (null != adapter) {
				adapter.sessions = adapter.sessionList.toArray(new HDSession[adapter.sessionList.size()]);
				adapter.notifyDataSetChanged();
			}
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case HANDLER_MESSAGE_REFRESH_LIST:
					refreshList();
					break;
				default:
					break;
			}

		}
	}


	public void setOnItemClickListener(OnItemClickListener listener) {
		this.clickListener = listener;
	}

	public CurrentSessionAdapter(FragmentActivity context, SwipeRefreshLayout mSwipeLayout) {
		this.mContext = context;
		this.mActivity = context;
		this.mSwipeLayout = mSwipeLayout;
		handler = new WeakHandler(this);
		sessionList = CurrentSessionManager.getInstance().getSessions();
		addrList.clear();
		nameList.clear();
	}

	@Override
	public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
		View convertView = LayoutInflater.from(mContext).inflate(R.layout.row_chat_history, viewGroup, false);
		return new MyViewHolder(convertView);
	}

	public void refresh() {
		if (handler.hasMessages(HANDLER_MESSAGE_REFRESH_LIST)) {
			return;
		}
		Message msg = handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST);
		handler.sendMessage(msg);
	}

	private void getUserInfo(long id, final MyViewHolder viewHolder, final int position) {
		ApiService apiService = HKHttpUtils.getApiService();
		retrofit2.Call<BaseResponse<User>> call = apiService.getUserById(MainActivity.ticket,String.valueOf(id));
		call.enqueue(new HKResponseResultCallBack<User>() {
			@Override
			public void onSuccess(User user) {
				if(user != null){
					//地址显示
					if(!TextUtils.isEmpty(user.getHomeAddress())){
						viewHolder.tvMessageAddr.setText(user.getHomeAddress());
						if(!addrList.containsKey(position)){
							addrList.put(position, user.getHomeAddress());
						}
					}else {
						viewHolder.tvMessageAddr.setText("");
						if(!addrList.containsKey(position)){
							addrList.put(position, "");
						}
					}

					//名字展示
					if (!TextUtils.isEmpty(user.getName())) {
						viewHolder.nameTextView.setText(user.getName());
					} else if (!TextUtils.isEmpty(user.getWxName())) {
						try {
							viewHolder.nameTextView.setText(URLDecoder.decode(user.getWxName(), "utf-8"));
						} catch (UnsupportedEncodingException e) {
							viewHolder.nameTextView.setText(user.getWxName());
						}
					}else {

					}
					if(!nameList.containsKey(position)){
						nameList.put(position, viewHolder.nameTextView.getText().toString());
					}

					if (user.getIsVip() == 1){
						viewHolder.vipIcon.setVisibility(View.VISIBLE);
					}else {
						viewHolder.vipIcon.setVisibility(View.GONE);
					}
//<<<<<<< HEAD
//				});
//
//			}
//
//			@Override
//			public void onResponse(Call call, Response response) throws IOException {
//
//				final String res = response.body().string();
//				final UserInfo result = CommonUtils.parseJsonWithGson(res, UserInfo.class);
//				mActivity.runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//					if(result.getData() != null){
//						//地址显示
//						if(!TextUtils.isEmpty(result.getData().getHomeAddress())){
//							viewHolder.tvMessageAddr.setText(result.getData().getHomeAddress());
//							if(!addrList.containsKey(position)){
//								addrList.put(position, result.getData().getHomeAddress());
//							}
//						}
//
//						//名字展示
//						if (!TextUtils.isEmpty(result.getData().getName())) {
//							viewHolder.nameTextView.setText(result.getData().getName());
//						} else if (!TextUtils.isEmpty(result.getData().getWxName())) {
//							try {
//								viewHolder.nameTextView.setText(URLDecoder.decode(result.getData().getWxName(), "utf-8"));
//							} catch (UnsupportedEncodingException e) {
//								viewHolder.nameTextView.setText(result.getData().getWxName());
//							}
//=======
					//名字展示
//					if (!TextUtils.isEmpty(user.getName())) {
//						viewHolder.nameTextView.setText(user.getName());
//					} else if (!TextUtils.isEmpty(user.getWxName())) {
//						try {
//							viewHolder.nameTextView.setText(URLDecoder.decode(user.getWxName(), "utf-8"));
//						} catch (UnsupportedEncodingException e) {
//							viewHolder.nameTextView.setText(user.getWxName());
////>>>>>>> master-temp
//						}
//					}

//<<<<<<< HEAD
//						if(!nameList.containsKey(position)){
//							nameList.put(position, viewHolder.nameTextView.getText().toString());
//						}

						//保存数据
//						if(sessionList.size() > position){
//							sessionList.get(position).getUser().setUsername(result.getData().getHomeAddress());
//							if(!TextUtils.isEmpty(result.getData().getName())){
//								sessionList.get(position).getUser().setNicename(result.getData().getName());
//							}else if(!TextUtils.isEmpty(result.getData().getWxName())){
//								sessionList.get(position).getUser().setNicename(result.getData().getWxName());
//							}
//						}

//=======
					//保存数据
//					if(sessionList.size() > position){
//						sessionList.get(position).getUser().setUsername(user.getHomeAddress());
//						if(!TextUtils.isEmpty(user.getName())){
//							sessionList.get(position).getUser().setNicename(user.getName());
//						}else if(!TextUtils.isEmpty(user.getWxName())){
//							sessionList.get(position).getUser().setNicename(user.getWxName());
//						}
//>>>>>>> master-temp
//					}

				}
			}

			@Override
			public void onGetDataFailed(int cd, String msg) {
				Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onFailed(retrofit2.Call call, Throwable t) {
				Toast.makeText(mContext, "请求失败", Toast.LENGTH_SHORT).show();
			}
		});


//		OkHttpClient okHttpClient = new OkHttpClient();
//
//		RequestBody body = new FormBody.Builder()
//				.add("uid", String.valueOf(id))
//				.build();
//
//		Request request = new Request.Builder()
//				.url(BuildConfig.API_URL + "account/findUserById")
//				.post(body)
//				.build();
//
//		Call call = okHttpClient.newCall(request);
//
//		call.enqueue(new Callback() {
//			@Override
//			public void onFailure(Call call, IOException e) {
//				e.printStackTrace();
//				mActivity.runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						Toast.makeText(mContext, "请求失败", Toast.LENGTH_SHORT).show();
//					}
//				});
//
//			}
//
//			@Override
//			public void onResponse(Call call, Response response) throws IOException {
//
//				final String res = response.body().string();
//				final UserInfo result = CommonUtils.parseJsonWithGson(res, UserInfo.class);
//				mActivity.runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//					if(result.getData() != null){
//						//地址显示
//						if(!TextUtils.isEmpty(result.getData().getHomeAddress())){
//							viewHolder.tvMessageAddr.setText(result.getData().getHomeAddress());
//						}
//						//名字展示
//						if (!TextUtils.isEmpty(result.getData().getName())) {
//							viewHolder.nameTextView.setText(result.getData().getName());
//						} else if (!TextUtils.isEmpty(result.getData().getWxName())) {
//							try {
//								viewHolder.nameTextView.setText(URLDecoder.decode(result.getData().getWxName(), "utf-8"));
//							} catch (UnsupportedEncodingException e) {
//								viewHolder.nameTextView.setText(result.getData().getWxName());
//							}
//						}
//
//						//保存数据
//						if(sessionList.size() > position){
//							sessionList.get(position).getUser().setUsername(result.getData().getHomeAddress());
//							if(!TextUtils.isEmpty(result.getData().getName())){
//								sessionList.get(position).getUser().setNicename(result.getData().getName());
//							}else if(!TextUtils.isEmpty(result.getData().getWxName())){
//								sessionList.get(position).getUser().setNicename(result.getData().getWxName());
//							}
//						}
//
//					}
//					}
//				});
//
//			}
//		});

	}


	@SuppressLint("RecyclerView")
	@Override
	public void onBindViewHolder(final MyViewHolder viewHolder, final int position) {
		if (sessions == null || position >= sessions.length || position < 0) {
			return;
		}
		HDSession sEntity = sessions[position];
		if (sEntity == null) {
			return;
		}
		if (sEntity.getUser() != null) {

			HDClient.getInstance().visitorManager().getCustomerDetailInfo(sEntity.getUser().getTenantId(), sEntity.getUser().getUserId(), new HDDataCallBack<CustomerInfoResponse.EntityBean>() {
				@Override
				public void onSuccess(final CustomerInfoResponse.EntityBean entityBean) {

					mActivity.runOnUiThread(new Runnable() {

						@Override
						public void run() {
							List<CustomerInfoResponse.EntityBean.ColumnValuesBean> columnValues = entityBean.getColumnValues();
							String truename = "";
							String nickname = "";
							for (int i = 0; i < columnValues.size(); i++) {
								String col_name = columnValues.get(i).getColumnName();
								String val = "";
								if(columnValues.get(i).getValues().size()>0){
									//更新后有改动-------更新前val = columnValues.get(i).getValues().get(0)
									val = columnValues.get(i).getValues().get(0).toString();
								}

								if(col_name.equals("username")){
									if(!TextUtils.isEmpty(val) && val.contains("#")){
										String uid = val.split("#")[0];
										getUserInfo(Long.parseLong(uid), viewHolder, position);
									}
								}else if(col_name.equals("truename")){
									truename = val;
									if (!TextUtils.isEmpty(truename)){
										viewHolder.nameTextView.setText(truename);
									}
								}else if(col_name.equals("nickname")){
									nickname = val;
									if (!TextUtils.isEmpty(nickname)) {
										viewHolder.nameTextView.setText(nickname);
									}
								}else if(col_name.equals("description")){
									Glide.with(mContext).load(val)
											.diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.drawable.default_customer_avatar).error(R.drawable.default_customer_avatar)
											.into(viewHolder.avatar);
								}
							}

							//名字显示
//							if (!TextUtils.isEmpty(truename)) {
//								viewHolder.nameTextView.setText(truename);
//							} else if (!TextUtils.isEmpty(nickname)) {
//								viewHolder.nameTextView.setText(nickname);
//							}
						}
					});
				}

				@Override
				public void onError(final int error, final String errorMsg) {
					if (mActivity == null) {
						return;
					}
					mActivity.runOnUiThread(new Runnable() {

						@Override
						public void run() {
							if (mSwipeLayout != null) {
								mSwipeLayout.setRefreshing(false);
							}
							Toast.makeText(mActivity, "获取用户信息失败，请稍后重试"+String.valueOf(error)+errorMsg, Toast.LENGTH_SHORT).show();
						}
					});
				}
			});

		}


		viewHolder.unReadMsgNum.setVisibility(View.INVISIBLE);
		viewHolder.itemView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (clickListener != null) {
					clickListener.onClick(viewHolder.itemView, position);
				}
			}
		});


		if (sEntity.hasUnReadMessage()) {
			viewHolder.unReadMsgNum.setVisibility(View.VISIBLE);
			if (sEntity.getUnReadMessageCount() <= 99) {
				viewHolder.unReadMsgNum.setText(sEntity.getUnReadMessageCount() + "");
			} else {
				viewHolder.unReadMsgNum.setText("99+");
			}
		} else {
			viewHolder.unReadMsgNum.setVisibility(View.GONE);
		}
		String originType = sEntity.getOriginType();
		if (originType != null) {
//			switch (originType) {
//				case "weibo":
//					viewHolder.tvOriginType.setImageResource(R.drawable.channel_weibo_icon);
//					break;
//				case "weixin":
//					viewHolder.tvOriginType.setImageResource(R.drawable.channel_wechat_icon);
//					break;
//				case "webim":
//					viewHolder.tvOriginType.setImageResource(R.drawable.channel_web_icon);
//					break;
//				case "app":
//					viewHolder.tvOriginType.setImageResource(R.drawable.channel_app_icon);
//					break;
//			}
		}

		HDMessage lastMessage = sEntity.getLastChatMessage();
		if (lastMessage == null) {
			viewHolder.tvTime.setText(DateUtils.getTimestampString(new Date(sEntity.getCreateDateTime())));
			viewHolder.tvMessage.setText("");
			return;
		}

		//取头像
//		JSONObject extJson = lastMessage.getExtJson();
//		if(extJson != null && extJson.has("weichat")) {
//			try {
//				JSONObject jsonWeichat = extJson.getJSONObject("weichat");
//				if(jsonWeichat != null) {
//					JSONObject visitorJson = jsonWeichat.getJSONObject("visitor");
//					if(visitorJson != null){
//						String url = visitorJson.getString("description");
//						Glide.with(mContext).load(url).asBitmap()
//								.diskCacheStrategy(DiskCacheStrategy.SOURCE).placeholder(R.drawable.default_customer_avatar).error(R.drawable.default_customer_avatar)
//								.into(viewHolder.avatar);
//					}
//				}
//
//			} catch (JSONException var3) {
//				var3.printStackTrace();
//			}
//
//		}

		if (MessageUtils.isRecallMessage(lastMessage)) {
			viewHolder.tvMessage.setText("[被撤回的消息]");
		} else if (lastMessage.getBody() == null) {
			viewHolder.tvMessage.setText("");
		} else if (lastMessage.getBody() instanceof HDVoiceMessageBody) {
			viewHolder.tvMessage.setText("[语音]");
		} else if (lastMessage.getBody() instanceof HDVideoMessageBody) {
			viewHolder.tvMessage.setText("[视频]");
		} else if (lastMessage.getBody() instanceof HDImageMessageBody) {
			viewHolder.tvMessage.setText("[图片]");
		} else if (lastMessage.getBody() instanceof HDNormalFileMessageBody) {
			viewHolder.tvMessage.setText("[文件]");
		} else if (lastMessage.getBody() instanceof HDTextMessageBody) {
//            viewHolder.tvMessage.setText(SmileUtils.getSmiledText(mContext, CommonUtils.convertStringByMessageText(((HDTextMessageBody) lastMessage.body).getMessage())),
//                    TextView.BufferType.SPANNABLE);
			SimpleCommonUtils.spannableEmoticonFilter(viewHolder.tvMessage, CommonUtils.convertStringByMessageText(((HDTextMessageBody) lastMessage.getBody()).getMessage()));
		}

		if (lastMessage.getTimestamp() > 0) {
			viewHolder.tvTime.setText(DateUtils.getTimestampString(new Date(lastMessage.getTimestamp())));
		} else if (sEntity.getCreateDateTime() > 0) {
			viewHolder.tvTime.setText(DateUtils.getTimestampString(new Date(sEntity.getCreateDateTime())));
		} else {
			viewHolder.tvTime.setText("");
		}
	}

	public HDSession getItem(int position) {
		if (sessions != null && position < sessions.length) {
			return sessions[position];
		}
		return null;
	}

	@Override
	public int getItemCount() {
		return sessions == null ? 0 : sessions.length;
	}

	@Override
	public Filter getFilter() {
		if (mFilter == null) {
			mFilter = new CurrentSessionFilter(sessionList, addrList, nameList);
		}
		return mFilter;
	}


	public static class MyViewHolder extends RecyclerView.ViewHolder {

		TextView nameTextView;
		ImageView avatar;
		TextView unReadMsgNum;
		TextView tvTime;
		TextView tvMessage;
		TextView tvMessageAddr;
		RelativeLayout list_item_layout;
		ImageView tvOriginType;
		ImageView vipIcon;

		public MyViewHolder(View itemView) {
			super(itemView);
			avatar = (ImageView) itemView.findViewById(R.id.avatar);
			nameTextView = (TextView) itemView.findViewById(R.id.name);
			unReadMsgNum = (TextView) itemView.findViewById(R.id.unread_msg_number);
			tvMessage = (TextView) itemView.findViewById(R.id.message);
			tvMessageAddr = (TextView) itemView.findViewById(R.id.message_arr);
			tvTime = (TextView) itemView.findViewById(R.id.time);
			list_item_layout = (RelativeLayout) itemView.findViewById(R.id.list_item_layout);
			tvOriginType = (ImageView) itemView.findViewById(originType);
			vipIcon = ((ImageView) itemView.findViewById(R.id.vip_icon));
		}
	}


	public class CurrentSessionFilter extends Filter {
		List<HDSession> mOriginalValues = null;
		Map<Integer, String> mAddrList = null;
		Map<Integer, String> mNameList = null;

		public CurrentSessionFilter(List<HDSession> list, Map<Integer, String> addrlist, Map<Integer, String> namelist) {
			this.mOriginalValues = list;
			this.mAddrList = addrlist;
			this.mNameList = namelist;
		}

		@Override
		protected FilterResults performFiltering(CharSequence prefix) {
			FilterResults results = new FilterResults();
			if (mOriginalValues == null) {
				mOriginalValues = new ArrayList<HDSession>();
			}
			if (prefix == null || prefix.length() == 0) {
				results.values = mOriginalValues;
				results.count = mOriginalValues.size();
			} else {
				String prefixString = prefix.toString();
				final int count = mOriginalValues.size();
				final ArrayList<HDSession> newValues = new ArrayList<HDSession>();
				for (int i = 0; i < count; i++) {
					final HDSession value = mOriginalValues.get(i);

					String valueText;
//					String roomText="";
					if (!TextUtils.isEmpty(value.getUser().getUsername())) {
						valueText = value.getUser().getUsername();
					} else {
						valueText = value.getUser().getUserId();
					}

//					if(!TextUtils.isEmpty(value.getUser().getUsername())){
//						roomText = value.getUser().getUsername();
//					}

					if (valueText.contains(prefixString) || (this.mNameList.containsKey(i) && this.mNameList.get(i).contains(prefixString)) || (this.mAddrList.containsKey(i) && this.mAddrList.get(i).contains(prefixString))) {
						newValues.add(value);
					}

				}

				results.values = newValues;
				results.count = newValues.size();
			}
			return results;
		}

		@Override
		protected void publishResults(CharSequence constraint, FilterResults results) {
			sessionList = (List<HDSession>) results.values;
			refresh();
		}
	}


}
